package edu.hawaii.duedates.email;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Provides basic email services for the Due Dates system. Instances of
 * Mailer can send an email message to an address with the smtp
 * server provided, containing a message pertaining to Due Dates.
 * 
 * @author Tyler Wolff and Scheller Sanchez
 *
 */
public class Mailer {
  
  /**
   * Sends out an email to a specified email address from specified smtp server, 
   * with a specified message. Returns true if email was sent. 
   * 
   * @param toAddr Email address to send message to.
   * @param smtp The name of smtp server.
   * @param body The body of the email message.
   * @return True if email is successfully sent out.
   * 
   */
  public boolean send(String toAddr, String smtp, String body) {
    
    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtp);
    Session session = Session.getInstance(props);
    
    try {
      Message msg = new MimeMessage(session);
      InternetAddress fromAddress = new InternetAddress("duedates-ulaula-discuss@googlegroups.com");
      InternetAddress userAddress = new InternetAddress(toAddr);
      msg.setFrom(fromAddress);
      msg.setRecipient(Message.RecipientType.TO, userAddress);
      msg.setSubject("DueDates Notification: " + new Date().toString());
      msg.setSentDate(new Date());
      msg.setText(body);
      Transport.send(msg);
      return true;
    }
    catch (MessagingException me) {
      System.out.println(me.getMessage());
      return false;
    }     
  }
}